import store from '@/store'
import config from '@/config'
import { LoginName } from '@/router/modules/login'

export function createRouterGuards(router) {
  router.beforeEach((to, from, next) => {
    if (store.getters.token) {
      // 进入登录页则直接重定向站点首页
      if (to.name === LoginName) {
        next({ path: config.homePath })
      } else {
        next()
      }
    } else {
      // 未登录
      if (to.meta.requireAuth) {
        // 页面开启登录权限，跳转至登录页
        next({ name: LoginName, query: { redirect: to.fullPath }, replace: true })
      } else {
        next()
      }
    }
  })

  router.onError((error) => {
    console.error(error, '路由错误') // eslint-disable-line no-console
  })
}
